package com.brotherly.mpgp.remoteinterface;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.brotherly.framework.event.EventService;
import com.brotherly.framework.service.IService;
import com.brotherly.framework.service.ServiceManager;
import com.brotherly.framework.storage.SimpleStorageService;
import com.brotherly.mpgp.util.GameManagerUtil;

public class RemoteServerService implements IService
{
    public static final String ACTION_GAME_IDENTIFIER = "ACTION_GAME_IDENTIFIER";
    public static final String ACTION_GAME_TAGS = "ACTION_GAME_TAGS";
    public static final String ACTION_GAME_RANKNAMES = "ACTION_GAME_RANKNAMES";
    public static final String ACTION_GAME_RECOMMENDS = "ACTION_GAME_RECOMMENDS";
    public static final String ACTION_GAME_RANK = "ACTION_GAME_RANK";
    public static final String ACTION_GAME_DETAIL = "ACTION_GAME_DETAIL";

    public static final String ACTION_GAME_ARTICLES = "ACTION_GAME_ARTICLES";

    public static final String ACTION_SUGGESTION_COMMIT = "ACTION_SUGGESTION_COMMIT";

    public static final String ACTION_RAND_RECOMMEND = "ACTION_RAND_RECOMMEND";

    public static final String ACTION_PACKAGE_CHANGED = "ACTION_PACKAGE_CHANGED";

    public static final String description = "com.brotherly.mpgp.remoteinterface.RemoteServer";

    public static final String OPTION_DEFAULT = "option_default";
    public static final String OPTION_GUIDE = "option_guide";

    public static final String service = "com.brotherly.mpgp.remoteinterface.RemoteServer";

    public static final String RemoteServer_Event_RemoteServer_Error = "RemoteServer_Event_RemoteServer_Error";
    public static final String RemoteServer_Event_RemoteServer_Success = "RemoteServer_Event_RemoteServer_Success";

    public static final String STORAGE = "com.brotherly.mpgp.remoteinterface";

    private EventService eventService;

    private SimpleStorageService simpleStorageService;

    public RemoteServerService()
    {}

    public void init()
    {
        simpleStorageService = (SimpleStorageService) ServiceManager.getInstance().getService(
                ServiceManager.SIMPLESTORAGE_SERVICE);
        eventService = (EventService) ServiceManager.getInstance().getService(ServiceManager.EVENT_SERVICE);
    }

    public void gameIdentifier()
    {
        RemoteServerWatcher.getInstance().executeTask(new RemoteServerWatcher.RemoteServerTask()
        {
            @Override
            public void execute(String remoteServerRoot, RemoteServer server)
            {
                JSONArray games = server.gameIdentifier(remoteServerRoot, GameManagerUtil.ApplicationInfos
                        .keySet());
                if (games != null)
                {
                    eventService.signEvent(RemoteServer_Event_RemoteServer_Success,
                            ACTION_GAME_IDENTIFIER, games);
                } else
                {
                    eventService.signEvent(RemoteServer_Event_RemoteServer_Error,
                            ACTION_GAME_IDENTIFIER, games);
                }
            }
        });
    }

    public void gameArticles(final List<String> gameids, final int index, final int count)
    {
        RemoteServerWatcher.getInstance().executeTask(new RemoteServerWatcher.RemoteServerTask()
        {
            @Override
            public void execute(String remoteServerRoot, RemoteServer server)
            {

                JSONObject games = server.gameArticles(remoteServerRoot, gameids, index, count);
                if (games != null)
                {
                    eventService.signEvent(RemoteServer_Event_RemoteServer_Success,
                            ACTION_GAME_ARTICLES, games);
                } else
                {
                    eventService.signEvent(RemoteServer_Event_RemoteServer_Error,
                            ACTION_GAME_ARTICLES, games);
                }
            }
        });
    }

    public void gameTags()
    {
        RemoteServerWatcher.getInstance().executeTask(new RemoteServerWatcher.RemoteServerTask()
        {
            @Override
            public void execute(String remoteServerRoot, RemoteServer server)
            {
                JSONArray games = server.gameTags(remoteServerRoot);
                if (games != null)
                {
                    eventService.signEvent(RemoteServer_Event_RemoteServer_Success,
                            ACTION_GAME_TAGS, games);
                } else
                {
                    eventService.signEvent(RemoteServer_Event_RemoteServer_Error,
                            ACTION_GAME_TAGS, games);
                }
            }
        });
    }

    public void gameRankNames()
    {
        RemoteServerWatcher.getInstance().executeTask(new RemoteServerWatcher.RemoteServerTask()
        {
            @Override
            public void execute(String remoteServerRoot, RemoteServer server)
            {
                JSONArray games = server.gameRankNames(remoteServerRoot);
                if (games != null)
                {
                    eventService.signEvent(RemoteServer_Event_RemoteServer_Success,
                            ACTION_GAME_RANKNAMES, games);
                } else
                {
                    eventService.signEvent(RemoteServer_Event_RemoteServer_Error,
                            ACTION_GAME_RANKNAMES, games);
                }
            }
        });
    }

    public void gameRecommend(final String tag, final int index, final int count, final boolean isClearHistory)
    {
        RemoteServerWatcher.getInstance().executeTask(new RemoteServerWatcher.RemoteServerTask()
        {
            @Override
            public void execute(String remoteServerRoot, RemoteServer server)
            {
                List<String> gamesid = new ArrayList<String>();
                for (JSONObject game : GameManagerUtil.GameInfos)
                {
                    try
                    {
                        gamesid.add(game.getString("packageName"));
                    }
                    catch (JSONException e)
                    {
                        e.printStackTrace();
                    }
                }
                JSONObject games = server.gameRecommend(remoteServerRoot, gamesid
                        , tag, index, count);

                if (games != null)
                {
                    try
                    {
                        games.put("index", index);
                        games.put("requestcount", count);
                        games.put("isClearHistory", isClearHistory);
                        int totalCount = games.getInt("count");
                        boolean hasMore = false;
                        if (totalCount > (index + 1) * count)
                        {
                            hasMore = true;
                        }
                        games.put("hasMore", hasMore);
                    }
                    catch (Exception e)
                    {
                        e.printStackTrace();
                    }
                    eventService.signEvent(RemoteServer_Event_RemoteServer_Success,
                            ACTION_GAME_RECOMMENDS, games);
                } else
                {
                    eventService.signEvent(RemoteServer_Event_RemoteServer_Error,
                            ACTION_GAME_RECOMMENDS, null);
                }
            }
        });
    }

    public void gameRank(final String rankName)
    {
        RemoteServerWatcher.getInstance().executeTask(new RemoteServerWatcher.RemoteServerTask()
        {
            @Override
            public void execute(String remoteServerRoot, RemoteServer server)
            {
                List<String> gamesid = new ArrayList<String>();
                for (JSONObject game : GameManagerUtil.GameInfos)
                {
                    try
                    {
                        gamesid.add(game.getString("packageName"));
                    }
                    catch (JSONException e)
                    {
                        e.printStackTrace();
                    }
                }
                JSONObject jsonObject = server.gameRank(remoteServerRoot, rankName, gamesid);
                if (jsonObject != null)
                {
                    eventService.signEvent(RemoteServer_Event_RemoteServer_Success,
                            ACTION_GAME_RANK, jsonObject);
                } else
                {
                    eventService.signEvent(RemoteServer_Event_RemoteServer_Error,
                            ACTION_GAME_RANK, null);
                }
            }
        });
    }

    public void publishSuggestion(final String content)
    {
        RemoteServerWatcher.getInstance().executeTask(new RemoteServerWatcher.RemoteServerTask()
        {
            @Override
            public void execute(String remoteServerRoot, RemoteServer server)
            {
                int result = server.publishSuggestionToServer(remoteServerRoot, content);
                if (result == 200)
                {
                    eventService.signEvent(RemoteServer_Event_RemoteServer_Success,
                            ACTION_SUGGESTION_COMMIT, null);
                } else
                {
                    eventService.signEvent(RemoteServer_Event_RemoteServer_Error,
                            ACTION_SUGGESTION_COMMIT, null);
                }
            }
        });
    }

    public void randRecommendGames(final ArrayList<String> gameIds, final int count)
    {
        // TODO Auto-generated method stub
        RemoteServerWatcher.getInstance().executeTask(new RemoteServerWatcher.RemoteServerTask()
        {
            @Override
            public void execute(String remoteServerRoot, RemoteServer server)
            {
                JSONObject result = server.randRecommendGames(remoteServerRoot, gameIds, count);
                if (result != null)
                {
                    eventService.signEvent(RemoteServer_Event_RemoteServer_Success,
                            ACTION_RAND_RECOMMEND, result);
                } else
                {
                    eventService.signEvent(RemoteServer_Event_RemoteServer_Error,
                            ACTION_RAND_RECOMMEND, result);
                }
            }
        });
    }

    public void initDownLoad(final ArrayList<String> types, final ArrayList<String> identifiers, final String rankName,
            final int index, final int count)
    {
        RemoteServerWatcher.getInstance().executeTask(new RemoteServerWatcher.RemoteServerTask()
        {
            @Override
            public void execute(String remoteServerRoot, RemoteServer server)
            {
                JSONObject result = server.initDownLoad(remoteServerRoot, types, identifiers, rankName, index, count);
                if (result != null)
                {
                    eventService.signEvent(RemoteServer_Event_RemoteServer_Success,
                            ACTION_GAME_IDENTIFIER, result);
                } else
                {
                    eventService.signEvent(RemoteServer_Event_RemoteServer_Error,
                            ACTION_GAME_IDENTIFIER, result);
                }
            }
        });
    }

    public void gameDetail(final int gameref)
    {
        // TODO Auto-generated method stub
        RemoteServerWatcher.getInstance().executeTask(new RemoteServerWatcher.RemoteServerTask()
        {
            @Override
            public void execute(String remoteServerRoot, RemoteServer server)
            {
                JSONObject result = server.gameDetail(remoteServerRoot, gameref);
                try
                {
                    if (result != null && result.getInt("status") == 200)
                    {
                        eventService.signEvent(RemoteServer_Event_RemoteServer_Success,
                                ACTION_GAME_DETAIL, result.getJSONObject("body"));
                    } else
                    {
                        eventService.signEvent(RemoteServer_Event_RemoteServer_Error,
                                ACTION_GAME_DETAIL, result);
                    }

                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
            }
        });
    }
}
